from wheels.pi.aio import Exit
from wheels.pi.aio.System import System

from wheels.pi.net.ServiceHandler import ServiceHandler
from wheels.pi.net.Connector import Connector
from wheels.pi.net.TcpConnector import TcpConnector


class EchoHandler(ServiceHandler):

    def __init__(self):
        ServiceHandler.__init__(self)


    def open(self):
        print "Connection to", self._peer_stream.remote_address()
        while True:
            data = raw_input("> ")
            yield self._write(data);
            echo = yield self._read()
            if not echo:
                break
            print echo
        print "Closing connection"
        self.close()
        yield Exit()



class EchoConnector(Connector):

    def __init__(self):
        Connector.__init__(self, TcpConnector());


    def connect(self, remote_address):
        yield Connector.connect(self, EchoHandler(), remote_address)



def client(port):
    print "Connecting..."
    con = EchoConnector()
    yield con.connect(("", port))


sys = System()
sys.new_task(client(45000))
sys.main()
